import re

from openai import OpenAI
from configparser import ConfigParser

class TranslateOpenai():
    _instance = None

    API_URL_BASE = None
    API_KEY = None
    API_MODEL = None

    def __init__(self, path_config):
        # print("__init__")
        if self._instance is not None:
            return
        # 创建ConfigParser对象
        config = ConfigParser()
        # 读取配置文件
        # config.read('./files/config.inf', encoding='utf-8')
        config.read(path_config, encoding='utf-8')
        # 获取default部分的api_key
        self.API_URL_BASE = config.get('default', 'openai_api_url_base')
        self.API_KEY = config.get('default', 'openai_api_key')
        self.API_MODEL = config.get('default', 'openai_api_model')
        print("self.API_URL_BASE: ", self.API_URL_BASE)
        print("self.API_KEY: ", self.API_KEY)
        print("self.API_MODEL: ", self.API_MODEL)

    def __new__(cls, path_config):
        # print("__new__")
        if cls._instance is None:
            instance = super().__new__(cls)
            instance.__init__(path_config)  # 如果需要初始化操作
            cls._instance = instance
        return cls._instance

    def _get_text_after_chinese(self, sentence):
        # 寻找最后一个中文字符出现的位置
        match = re.search(r'([\u4e00-\u9fff]+)(.*)', sentence)
        if match:
            # 提取中文字符后面的部分
            chinese, rest_of_text = match.groups()
            return rest_of_text
        else:
            # 如果句子中没有中文字符，返回None或其他默认值
            return None

    def _contains_chinese_char(self, s):
        for char in s:
            if '\u4e00' <= char <= '\u9fff':
                return True
        return False

    def _get_from_desc(self, zh):
        try:
            zh_left = self._get_text_after_chinese(zh)
            print("zh_left:", zh_left)
            zh_left = zh_left[1:]
            zh_left_list = zh_left.split('"')
            print("zh_left_list[0]:", zh_left_list[1])
            return zh_left_list[1]
        except:
            return None


    def translate_text(self, text, source_language, target_language):
        client = OpenAI(api_key=self.API_KEY, base_url=self.API_URL_BASE)
        completion = client.chat.completions.create(
            model=self.API_MODEL,
            messages=[
                {"role": "system", "content": "You will be provided with a sentence in " + source_language
                                              + ", and your task is to translate it into " + target_language
                                              + ". Note that only the translated results are output"},
                {"role": "user", "content": text},
                {"role": "assistant", "content": "Translate the text to " + target_language
                                                 + ". Note that only the translated results are output"}
            ]
        )
        # print(completion)
        # print(completion.choices[0].message)
        # print(completion.choices[0].message.content)
        sentence = completion.choices[0].message.content
        if self._contains_chinese_char(sentence):
            sentence_parse = self._get_from_desc(sentence)
            if sentence_parse is not None:
                sentence = sentence_parse
        return sentence


    def translate_text_bak(self, text, target_language):
        client = OpenAI(api_key=self.API_KEY, base_url=self.API_URL_BASE)
        completion = client.chat.completions.create(
            model=self.API_MODEL,
            messages=[
                {"role": "system", "content": "You are a helpful assistant that translates text."},
                {"role": "user", "content": text},
                {"role": "assistant", "content": "Translate the text to " + target_language}
            ]
        )
        # print(completion)
        # print(completion.choices[0].message)
        # print(completion.choices[0].message.content)
        sentence = completion.choices[0].message.content
        if self._contains_chinese_char(sentence):
            sentence_parse = self._get_from_desc(sentence)
            if sentence_parse is not None:
                sentence = sentence_parse
        return sentence


    def testOpenaiZh2En(self):
        # 准备输入文本
        zh_text = "青桔柠檬百香果茶".encode('utf-8').decode('utf-8')
        # zh_text = "lalalalalala"
        en_text = self.translate_text(zh_text, "Chinese", "English")
        #
        print(f"英文原文: {zh_text}")
        print(f"中文翻译: {en_text}")


    def translateList(self, zh_list):
        #
        en_list = []
        #
        for zh in zh_list:
            translated_output = self.translate_text(zh, "Chinese", "English")
            en_list.append(translated_output)
            #
            print(f"中文原文: {zh}")
            print(f"英文翻译: {translated_output}")
            print("---------------------------------------")
        return en_list



if __name__ == '__main__':
    th = TranslateOpenai('../files/config.inf')
    th.testOpenaiZh2En()
